package com.yuanli.card.manage.controller;

import com.github.pagehelper.PageInfo;
import com.yuanli.card.authentication.service.ISysUserService;
import com.yuanli.card.manage.service.CardLogService;
import com.yuanli.card.manage.service.CardService;
import com.yuanli.card.pojo.CardLog;
import com.yuanli.card.pojo.SysUser;
import com.yuanli.card.req.CardLogQueryReq;
import com.yuanli.card.res.ResponseBean;
import com.yuanli.card.utils.JsonMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/cardLog")
public class CardLogController {


    @Resource
    private CardLogService cardLogService;
    @Resource
    private CardService cardService;
    @Resource
    private ISysUserService sysUserService;

    @GetMapping("/query")
    public ResponseBean query(CardLogQueryReq req) {
        if (StringUtils.isNotBlank(req.getIccid())) {
            req.setCardId(cardService.getByIccid(req.getIccid()).getId());
        }
        PageInfo<CardLog> pageInfo = cardLogService.query(req);
        Map<String, Object> data = new HashMap<>();
        data.put("total", pageInfo.getTotal());
        data.put("list", this.fillCardLog(pageInfo.getList()));
        return ResponseBean.success().setData(data);
    }

    private List<Map<String, Object>> fillCardLog(List<CardLog> list) {
        if (list == null) {
            return null;
        }
        return list.parallelStream().map(cardLog -> {
            Map<String, Object> map = JsonMapper.defaultMapper().json2Map(JsonMapper.defaultMapper().toJson(cardLog));
            SysUser user = sysUserService.findById(cardLog.getOperateCustomerId().longValue());
            map.put("customerName",user==null?null:user.getNickname());
            return map;
        }).collect(Collectors.toList());
    }
}
